close all
clear all
clc

filename = 'a.pdf';
fps = 18;
compression = 'msvc';
guard_time = 3;
movieH = 600;
movieW = 800;
DataFrameSize = 1024;

get_qrcode();

tic
base64_encoder(filename);
BFsize = getfilesize(filename);

Fsize = getfilesize('b64file');
LastBlock = rem(Fsize, DataFrameSize);
nImages = floor(Fsize/DataFrameSize);
file = file_get_contents('b64file');
assert(nImages < 1e6-1);

Map = [0,0,0;1,1,1];

% create avi object
aviobj = avifile('encode.avi', 'fps', fps, 'compression', compression);
content = sprintf('#start BFsize = %d; DataFrameSize = %d; nImages = %d; LastBlock = %d;\n', BFsize, DataFrameSize, nImages, LastBlock);
file_put_contents('data', content);
generate_png(8);
img = embedimg(movieH, movieW, imread('tmp.png'));
%F = im2frame( repmat(double(img), [1,1,3]) );
F = im2frame(uint8(img), Map);
for n = 1:guard_time*fps
    aviobj = addframe(aviobj,F);
end


for k = 1:nImages
    num = sprintf('[%06d]', k);
    content = [num, '<',file((k-1)*DataFrameSize+1 : k*DataFrameSize), '>'];
    assert(length(content) == DataFrameSize+10);
    file_put_contents('data', content);
    generate_png(5);
    img = embedimg(movieH, movieW, imread('tmp.png'));
    %F = im2frame( repmat(double(img), [1,1,3]) );
    F = im2frame(uint8(img), Map);
    aviobj = addframe(aviobj, F);
    
    if rem(k, 64) == 0
        fprintf('frame processed = %d\n', k);
    end
end

if LastBlock ~= 0
    num = sprintf('[%06d]', nImages+1);
    file_put_contents('data', [num, '<', file(end-LastBlock+1:end), '>']);
    generate_png(5);
    img = embedimg(movieH, movieW, imread('tmp.png'));
    %F = im2frame( repmat(double(img), [1,1,3]) );
    F = im2frame(uint8(img), Map);
    aviobj = addframe(aviobj, F);
end



file_put_contents('data', '#end');
generate_png(10);
img = embedimg(movieH, movieW, imread('tmp.png'));
%F = im2frame( repmat(double(img), [1,1,3]) );
F = im2frame(uint8(img), Map);
for n = 1:fps
    aviobj = addframe(aviobj,F);
end


aviobj = close(aviobj);
toc

delete('qrcode.exe');
delete('b64file');
delete('tmp.png');
delete('data');

